/**
 * @file{同步 cf 精度检测工站库}
 */
 'use strict';

 const LRU = require("lru-cache");
 const schedule = require('node-schedule');
 const {initData} = require('../../model/jingdujiance/panel');

 const options = {
    max: 500,
    length: function (n, key) { return n * 2 + key.length },
    dispose: function (key, n) { n.close() },
    maxAge: 1000 * 60 * 60
 }
 /**
  * 同步精度检测工站数据父类
  */
 class JingduBase {

    constructor (panel, sequelize_source, sequelize_aim, stationName) {
        // 初始化缓存
        this.cache = new LRU(options);
        this.panel = panel;
        this.sequelize_source = sequelize_source;
        this.sequelize_aim = sequelize_aim;
        this.stationName = stationName;
        // 初始化panel表
        initData(this.sequelize_aim);
        // 开始定时缓存任务
        let job = schedule.scheduleJob('*/2 * * * * *', () => {
            this.getSourceCubeInfo();
        })
    }
    /**
     * 获取精度检测表信息
     */
    async getSourceCubeInfo () {
        let res = await this.panel.findLatestPanelInfo(this.sequelize_source);
        // 每片只取一次
        if (res.PID === this.currentPanelID) return false;
        this.currentPanelID = res.PID;
        // 部分数据转换 
        let panelInfo = {
            ...res,
            is_ok: res.result == 'OK' ? 1 : 0,
            gen_time_str: String(res.createtime),
            save_path: res.imagePath,
            panel_id: res.PID
        }
        //缓存
        this.cache.set(this.currentPanelID + 'panel', panelInfo);
        //上传
        this.postDataToLineDb(panelInfo);
    }
    /**
     * 上传到目标库
     * @param {Object} data 目标库字段数据
     */
    async postDataToLineDb (data) {
        //上传
        try {
            let res = await this.panel.uploadPanelInfo(data);
            if(res.dataValues.uid) {
                console.log(`panel上传${this.stationName}库Psucess!`);
            }
        } catch (error) {
            console.log(`panel上传${this.stationName}库fail`);
        }
    }
    /**
     *  获取对应panel信息并清除对应缓存
     * @param {String} panelId
     * @returns panel信息
     */
    getPanelInfoFromCache (panelId) {
        let panelInfo = this.cache.get(panelId);
        this.cache.del(panelId);
        return panelInfo;
    }
 }

 module.exports = JingduBase;